import Taro from "@tarojs/taro";
import getBaseUrl from "./httpBaseUrl";

let httpNum = 0; //用于处理并发接口时，当最后一个接口请求结束时loading关闭。
//默认get 可传递POST
export function HttpRequest(url,data, method = "GET",contentType) {
  Taro.showLoading({ title: "加载中", mask: true });
  httpNum++;
  return new Promise((resolve, reject) => {
    Taro.request({
      url: getBaseUrl() + url,
      data: data,
      method: method,
      header: {
        "content-type": contentType ? contentType : "application/json",
        Authorization: Taro.getStorageSync("tokenInfo"),
      },
      success(res) {
        httpNum--;
        httpNum === 0 && Taro.hideLoading();
        resolve(res.data);
      },
      fail(err) {
        httpNum--;
        httpNum === 0 && Taro.hideLoading();
        const errRes = err.hasOwnProperty("data")
          ? err.data
          : { succeed: false, errorMsg: "请求异常" };
        reject(errRes);
      },
    });
  });
}
export function httpPost(url,data){
  return HttpRequest(url,data,"POST")
}
export function httpGet(url,data){
  return HttpRequest(url,data,"GET")
}

